package org.jeecg.modules.system.aspect;

import com.alibaba.fastjson.JSONObject;
import com.xjgc.xjap.utils.BusinessLogger;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.IPUtils;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.system.entity.SysLog;
import org.jeecg.modules.system.service.ISysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;


/**
 * 系统日志，切面处理类
 *
 * @Author scott
 * @email jeecgos@163.com
 * @Date 2018年1月14日
 */
@Aspect
@Component
public class AutoLogAspect {

    @Autowired
    private ISysLogService sysLogService;

    @Pointcut("@annotation(org.jeecg.common.aspect.annotation.AutoLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        Object result = null;
        String isException;
        try {
            //执行方法
            result = point.proceed();
            isException = "false";
        } catch (Exception e) {
            isException = "true";
        }
        //执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;

        //保存日志
        saveSysLog(point, time, isException);
        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time, String isException) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLog sysLog = new SysLog();
        AutoLog syslog = method.getAnnotation(AutoLog.class);

        String sysLogValue = null;
        if (syslog != null) {
            //注解上的描述,操作日志内容
            sysLogValue = syslog.value();
            sysLog.setLogContent(syslog.value());
            sysLog.setLogType(syslog.logType());
        }
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);

        String apiOperationValue = null;
        if (apiOperation != null) {
            apiOperationValue = apiOperation.value();
        }
        RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);

        String str = Arrays.toString(requestMapping.method());
        String requestMethod = str.substring(1, str.length() - 1);

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");


        //设置操作类型
        if (sysLog.getLogType() == CommonConstant.LOG_TYPE_2) {
            sysLog.setOperateType(getOperateType(methodName, syslog.operateType()));
        }

        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params = "{}";
        try {
            params = JSONObject.toJSONString(args);
            sysLog.setRequestParam(params);
        } catch (Exception e) {
        }
        //获取request
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

//		//获取登录用户信息
//		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
//		if(sysUser!=null){
//			sysLog.setUserid(sysUser.getUsername());
//			sysLog.setUsername(sysUser.getRealname());
//		}
        //耗时
        sysLog.setCostTime(time);
        sysLog.setCreateTime(new Date());

        String userId = (String) request.getSession().getAttribute("userId");
        String userName = (String) request.getSession().getAttribute("userName");
        sysLog.setUserid(userId);
        sysLog.setUsername(userName);
        //保存系统日志
        sysLogService.save(sysLog);

        String requestURI = request.getRequestURI();
        String localAddr = request.getLocalAddr();

        String header = request.getHeader("X-Real-IP");

    String resultMessage = "false".equals(isException) ? "成功" : "失败";
    String eventLogDescribe = "用户【"+userName + "】执行了【" + apiOperationValue + "】,执行结果是【" + resultMessage + "】";

//		//添加日志信息
        BusinessLogger.logger(userId, sysLogValue, requestURI, params, requestMethod, header, localAddr, eventLogDescribe, isException);
}

    /**
     * 获取操作类型
     */
    private int getOperateType(String methodName, int operateType) {
        if (operateType > 0) {
            return operateType;
        }
        if (methodName.startsWith("list")) {
            return CommonConstant.OPERATE_TYPE_1;
        }
        if (methodName.startsWith("add")) {
            return CommonConstant.OPERATE_TYPE_2;
        }
        if (methodName.startsWith("edit")) {
            return CommonConstant.OPERATE_TYPE_3;
        }
        if (methodName.startsWith("delete")) {
            return CommonConstant.OPERATE_TYPE_4;
        }
        if (methodName.startsWith("import")) {
            return CommonConstant.OPERATE_TYPE_5;
        }
        if (methodName.startsWith("export")) {
            return CommonConstant.OPERATE_TYPE_6;
        }
        return CommonConstant.OPERATE_TYPE_1;
    }
}
